﻿using System;
using System.Threading.Tasks;
using AspectCore.DynamicProxy;

namespace HystrixCoreDemo.Models
{
    [AttributeUsage(AttributeTargets.Method)]
    class HystrixCommandAttribute : AbstractInterceptorAttribute
    {
        private string fallbackMethod;

        public HystrixCommandAttribute(string fallbackMethodName)
        {
            this.fallbackMethod = fallbackMethodName;
        }

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            try
            {
                Console.WriteLine("拦截之前");

                await next(context);

                Console.WriteLine("拦截之后");
            }
            catch (Exception exp)
            {
                Console.WriteLine("调用异常");

                //1、获得降级方法（根据对象获取类，从类中获取降级方法）
                //2、调用降级方法
                //3、返回降级方法的返回值

                var methodInfo = context.Implementation.GetType().GetMethod(fallbackMethod);

                var result = methodInfo.Invoke(context.Implementation, context.Parameters);

                context.ReturnValue = result;

            }
        }
    }
}
